package fr.uha.ensisa.kfetmanager.customer.admin;

import fr.uha.ensisa.kfetmanager.category.CustomerCategory;
import fr.uha.ensisa.kfetmanager.category.CustomerCategoryManagerRemote;
import fr.uha.ensisa.kfetmanager.customer.Customer;
import fr.uha.ensisa.kfetmanager.customer.CustomerManagerRemote;
import java.io.IOException;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author JC
 */
@WebServlet(name="AdminCustomersCreate", urlPatterns={"/admin/customers/create"})
public class AdminCustomersCreate extends HttpServlet {

    @EJB
    private CustomerManagerRemote customerManager;

    @EJB
    private CustomerCategoryManagerRemote categoryManager;

    private final String errorPage = "/error.jsp";
    private final String create = "/admin/customers/create";
    private final String home = "/admin/customers";

 
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        // If the method is GET, forward request to AdminCustomers.jsp to display the form.
        // If the method is POST, get all the parameters and perform actual create

        if (request.getMethod().equals("GET")) {
            // Get a list of all categories and forward it to the JSP page (for <option>s)
            List<CustomerCategory> list = categoryManager.getCategories();
            this.getServletContext().setAttribute("categoryList", list);
            this.getServletContext().setAttribute("action", "create");
            this.getServletContext().getRequestDispatcher("/admin/AdminCustomers.jsp").forward(request, response);

        } else {
            String firstName = request.getParameter("firstName");
            String lastName = request.getParameter("lastName");
            String nickname = request.getParameter("nickname");
            String cotisantString = request.getParameter("cotisant");
            String gerantKfetString = request.getParameter("gerantKfet");
            String balanceString = request.getParameter("balance");
            String categoryIdString = request.getParameter("categoryId");

            // Check if all parameters have been specified
            if (firstName == null || lastName == null || nickname == null || cotisantString == null
                    || gerantKfetString == null || balanceString == null || categoryIdString == null) {
                this.getServletContext().setAttribute("errorMessage", "Un param&egrave;tre n'a pas &eacute;t&eacute; sp&eacute;cifi&eacute;");
                this.getServletContext().setAttribute("redirectTo", create);
                this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
                return;
            }

            // Check if any parameter is empty string (except nickname, that's ok)
            if (firstName.equals("") ||
                    lastName.equals("") ||
                    cotisantString.equals("") ||
                    gerantKfetString.equals("") ||
                    balanceString.equals("") ||
                    categoryIdString.equals("")) {
                this.getServletContext().setAttribute("errorMessage", "Un param&egrave;tre est vide");
                this.getServletContext().setAttribute("redirectTo", create);
                this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
                return;
            }


            // If nickname is empty, set it to match the last name
            if (nickname.equals("")) nickname = lastName;

            // Check if nickname already exists
            if (customerManager.exists(nickname)) {
                this.getServletContext().setAttribute("errorMessage", "Cet alias existe d&eacute;j&agrave;");
                this.getServletContext().setAttribute("redirectTo", create);
                this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
                return;
            }

            // Parse the cotisant and gerantKfet parameters
            Boolean cotisant = Boolean.valueOf(cotisantString);
            Boolean gerantKfet = Boolean.valueOf(gerantKfetString);

            // Parse the categoryId and balance parameters
            Long categoryId;
            Double balance;
            try {
                categoryId = Long.valueOf(categoryIdString);
                balance = Double.valueOf(balanceString);
            } catch (NumberFormatException e) {
                this.getServletContext().setAttribute("errorMessage", "categoryId invalide");
                this.getServletContext().setAttribute("redirectTo", create);
                this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
                return;
            }

            // Fetch the category using the specified Id
            CustomerCategory cat = categoryManager.getCategory(categoryId);

            if (cat == null) {
                this.getServletContext().setAttribute("errorMessage", "Pas de cat&eacute;gorie avec cet Id");
                this.getServletContext().setAttribute("redirectTo", create);
                this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
                return;
            }

            // Create customer
            try {
                customerManager.createCustomer(new Customer(), firstName, lastName,
                        nickname, cotisant, gerantKfet, balance, cat);
            } catch (Exception e) {
                this.getServletContext().setAttribute("errorMessage", "Erreur lors de la cr&eacute;ation de client");
                this.getServletContext().setAttribute("redirectTo", create);
                this.getServletContext().getRequestDispatcher(errorPage).forward(request, response);
                return;
            }

            // Redirect to home page
            response.sendRedirect(getServletContext().getContextPath() + home);
        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
